package com.kmvc.message.activity;

import java.io.File;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.kmvc.message.R;
import com.kmvc.message.adapter.WebviewAdapternew;
import com.kmvc.message.database.DbHelper;
import com.kmvc.message.encryption.Encryption;
import com.kmvc.message.entity.StringEntity;
import com.kmvc.message.handler.StringHandler;
import com.kmvc.message.tools.WebService;
import com.kmvc.ui.IphoneTitleBarActivity;

@SuppressLint("SimpleDateFormat")
public class MessageShowActivity extends IphoneTitleBarActivity
{
	private ListView lv;
	private String area, datString;
	AlertDialog al;
	private String message;
	private Handler h = new Handler();
	AlertDialog.Builder builder;
	private ProgressDialog progress;
	// List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();;
	private List<StringEntity> mStringList = new ArrayList<StringEntity>();
	//private DbHelper dbhelper = new DbHelper(Messageother.this);
	private WebviewAdapternew adapter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		//
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.listview);
		lv = (ListView) findViewById(R.id.mylistview);
		ClearWebViewCache();
		setLeftButton(R.string.goback,null);
		
		Intent intent = getIntent();
		SharedPreferences shp = getSharedPreferences("lastarea", 0);
		try {
			area = intent.getStringExtra("area") + "";
			datString = intent.getStringExtra("datestring");
			if (!area.equals("null")) {
				Editor editor = shp.edit();
				editor.putString("area", area);
				editor.putString("datString", datString);
				editor.commit();
			} else {
				area = shp.getString("area", "信息通报");
				datString = shp.getString("datString", "");
			}

		} catch (Exception e) {

			e.toString();

		}
		setTitle(area);

	}

	private void ClearWebViewCache() {
		//
		Context context = this;
		File file = new File(getCacheDir() + "/webviewCacheChromium"); // 获取缓存文件目录
		if (file != null && file.exists() && file.isDirectory()) {
			for (File item : file.listFiles()) {
				item.delete();
			}
			file.delete();
		}
		context.deleteDatabase("webview.db");// 删除数据库
		context.deleteDatabase("webviewCache.db");
		try {
			System.gc();
		} catch (Exception e) {
			e.toString();
		}

	}

	@Override
	public void onResume() {

		super.onResume();
		ShowData();
	}

	@Override
	protected void onDestroy() {

		super.onDestroy();
		try {
 			WebviewAdapternew.webView.setVisibility(View.GONE);
 			WebviewAdapternew.webView.destroy();			 
			 
		} catch (Exception e) {

			Log.e("Messageother125", e.toString());
		}
		this.finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		//
		try {
			progress.dismiss();
		} catch (Exception e) {
			e.toString();
		}
		if (keyCode == KeyEvent.KEYCODE_BACK) 
		{
			this.finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	private void ShowData() {
		//
		getData();
		adapter = new WebviewAdapternew(this, mStringList, area,datString);
		lv.setAdapter(adapter);
	}

	private List<StringEntity> getData() {

		mStringList.clear();
		 
		// Cursor c = db.selecthistory();
		DbHelper dbhelper = new DbHelper(MessageShowActivity.this);
		Cursor c =dbhelper.selecthistorynew(area, datString);
		while (c.moveToNext()) {

			StringEntity entity = new StringEntity();
			entity.ID = c.getString(c.getColumnIndex("id"));
			entity.Start_Time = c.getString(c.getColumnIndex("sendDate"));
			String conString=c
					.getString(c.getColumnIndex("Content")).replace("*", "<")
					.replace("^", ">");
			if (conString.getBytes().length==conString.length() && !conString.contains(".")) {
				try {
					conString=Encryption.decode(conString);
				} catch (Exception e) {
				 
				}
				
			}
			entity.Content =conString;
			if (!mStringList.contains(entity)) {
				mStringList.add(entity);
			}
		}
		c.close();
		dbhelper.close();
		if (c.getCount() == 0) {
			SimpleDateFormat formatter = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			Date newdate = new Date(System.currentTimeMillis());// 获取当前时间
			StringEntity entity = new StringEntity();
			entity.ID = "-1";
			entity.Start_Time = formatter.format(newdate);
			entity.Content = "暂时没有信息";
			mStringList.add(entity);
		}
		return mStringList;

	}


	Runnable r = new Runnable() {
		public void run() {
			DbHelper dbhelper = new DbHelper(MessageShowActivity.this);
			try {
				dbhelper.inserthistorybyListnew(mStringList);
			 
			} catch (Exception e) {
			 
			}			
			dbhelper.close();
			progress.dismiss();
			Toast.makeText(MessageShowActivity.this, "刷新成功!", Toast.LENGTH_LONG)
					.show();
			ShowData();
		}
	};

	protected void RefshData() {

		progress = ProgressDialog.show(this, "请稍候", "刷新数据中...", true);
		progress.setCancelable(true);
		DbHelper dbHelper = new DbHelper(MessageShowActivity.this);
		final int messageCount = dbHelper.getTodayMessageCount();
		dbHelper.close();
		new Thread() {
			public void run() {

				try {
					TelephonyManager mTelephonyMgr = (TelephonyManager) MessageShowActivity.this
							.getSystemService(Context.TELEPHONY_SERVICE);
					String IMSI = null;
					String MolNo = null;
					try {
						IMSI = mTelephonyMgr.getSubscriberId();
						MolNo = mTelephonyMgr.getDeviceId();
					} catch (Exception e) {
						e.printStackTrace();
					}
					final SharedPreferences settingSharedPreferences = getSharedPreferences(
							"phonenumber", 0);
					String tempimsi = settingSharedPreferences.getString(
							"IMSI", "");
					String tempmolno = settingSharedPreferences.getString(
							"MolNo", "");
					if (IMSI.equals(tempimsi) && MolNo.equals(tempmolno)) {
						message = "<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>"
								+ WebService.RefshCDMA(IMSI, MolNo,
										messageCount);
						if (!message
								.equals("<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>null")
								&& !message
										.equals("<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><data></data>")) {

							StringReader read = new StringReader(message);
							InputSource mInputSource = new InputSource(read);
							try {
								SAXParserFactory msSaxParserFactory = SAXParserFactory
										.newInstance();
								SAXParser msSaxParser = msSaxParserFactory.newSAXParser();
								XMLReader msXmlReader = msSaxParser.getXMLReader();
								StringHandler mStringHandler = new StringHandler();
								msXmlReader.setContentHandler(mStringHandler);
								msXmlReader.parse(mInputSource);
								mStringList.clear();
								mStringList = mStringHandler.getParsedData();								
							} catch (Exception e) {
								e.toString();
							}

						} else {
							Log.d("kmvc", "没读取到数据");
						}
					}

				} catch (Exception e) {
					progress.dismiss();
				}
				h.post(r);
			}
		}.start();

	}

}
